package com.rh.i_mes.filter;

/**
 * 拦截器
 * @author XiaoHui
 *
 */

import com.alibaba.fastjson.JSONObject;
import com.rh.i_mes.common.model.SysConst;
import com.rh.i_mes.common.service.RedisService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Component
public class UserInterceptor implements HandlerInterceptor {

	@Autowired
	private RedisService redisService;
	private final Logger logger = LoggerFactory.getLogger(UserInterceptor.class);

	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {

	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {

	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
		response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
		response.setHeader("Access-Control-Max-Age", "7200");
		response.setHeader("Access-Control-Allow-Credentials", "true");
		response.setHeader("Access-Control-Allow-Headers", "Accept,X-Requested-With,Content-Type,"+ SysConst.token);
		response.setHeader("Access-Control-Allow-Origin", "*");
		String method = request.getMethod();
		if(method.equalsIgnoreCase("options")){
			response.setCharacterEncoding("UTF-8");
			response.setContentType("application/json;charset=UTF-8");
			response.getWriter().write("");
			return false;
		}
		String token = request.getHeader(SysConst.token);
		Object o=null;
		if (token!=null){
			o= redisService.get(token);
		}
		//不为空，已登录放行；
		System.out.println(o+"进入拦截器");
		if(o!=null){
			//放行
			System.out.println("放行");
			return true;
		}
		nologin(response);
		System.out.println("拦截");
		return false;
	}
	public void nologin(HttpServletResponse response){
		try {

			//返回未登录的json
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("resp_msg","与服务器断开连接，请重新登录");
			jsonObject.put("resp_code",202);
			jsonObject.put("datas","");
			//重置response
			//response.reset();
			//设置编码格式
			response.setCharacterEncoding("UTF-8");
			response.setContentType("application/json;charset=UTF-8");
			PrintWriter pw = response.getWriter();
			pw.write(jsonObject.toString());
			pw.flush();
			pw.close();
		}catch (Exception e){
			logger.error(e.toString());
		}

	}
}

